
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import common.CommonTools;

public class UDPClient implements Runnable {

	static int bufferSize = 1000;
	private String serverName = null;
	private int UDPPort = 0;
	private String geolocation = null;
	private String geolocationCaller = null;

	private String result = null;

	public UDPClient(String serverName, int uDPPort, String geolocation,
			String geolocationCaller) {
		super();
		this.serverName = serverName;
		UDPPort = uDPPort;
		this.geolocation = geolocation;
		this.geolocationCaller = geolocationCaller;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void run() {
		DatagramSocket clientSocket = null;

		byte[] bufferOut = new byte[bufferSize];
		byte[] bufferIn = new byte[bufferSize];
		// String result = "000";

		InetAddress serverAddress;

		try {
			serverAddress = InetAddress.getByName(serverName);

			clientSocket = new DatagramSocket();
			bufferOut = geolocation.getBytes();
			DatagramPacket request = new DatagramPacket(bufferOut,bufferOut.length, serverAddress, UDPPort);
			clientSocket.send(request);
			
			CommonTools.writeLog("server", geolocationCaller,
					"A UDP Request sent to :" + geolocation + " server "
							+ " at " + UDPPort + " from " + geolocationCaller
							+ " server", "server");
			DatagramPacket reply = new DatagramPacket(bufferIn,
					bufferIn.length, serverAddress, UDPPort);
			clientSocket.receive(reply);
			result = (new String(reply.getData())).trim();
			
			CommonTools.writeLog("server", geolocationCaller,
					"A UDP response received from  :" + geolocation
							+ " server " + " with the result  " + result, "server");

		} catch (UnknownHostException e) {

			e.printStackTrace();
		} catch (Exception e) {

			e.printStackTrace();
		}
		// add close socket
		finally {
			if (clientSocket != null)
				clientSocket.close();
		}

	}

}
